package com.xy.tool.concurrent.locks.local;

import com.xy.tool.concurrent.locks.DisLock;
import com.xy.tool.concurrent.locks.DisLockFactory;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;

public class LocalDisLockFactory implements DisLockFactory, Closeable {

    private final ConcurrentMap<String, LockWrapper> lockMap = new ConcurrentHashMap<>();

    @Override
    public DisLock create() {
        return new LocalDisLock(this);
    }

    @Override
    public synchronized void close() throws IOException {
        LockWrapper lock;
        for(Map.Entry<String, LockWrapper> entry : lockMap.entrySet()) {
            lock = entry.getValue();
            if(lock != null) {
                lock.getLock().unlock();
            }
        }
        lockMap.clear();
    }

    public LockWrapper getOrCreateLock(String resource) {
        return lockMap.computeIfAbsent(resource, e -> new LockWrapper(new ReentrantLock()));
    }

    public LockWrapper get(String resource) {
        return lockMap.get(resource);
    }

}
